<template>
  <div class="role">
    <page-search
      :searchFormConfig="formConfig"
      @resetBtnClick="handleResetClick"
      @queryBtnClick="handleQueryClick"
    ></page-search>
    <page-content
      ref="pageContentRef"
      :contentTableConfig="contentTableConfig"
      pageName="role"
      @newBtnClick="handleNewData"
      @editBtnClick="handleEditData"
    ></page-content>
    <page-modal
      ref="pageModalRef"
      :modalConfig="modalConfig"
      pageName="role"
      :defaultInfo="defaultInfo"
      :otherInfo="otherInfo"
    >
      <div class="menu-tree">
        <el-tree
          ref="elTreeRef"
          :data="menus"
          show-checkbox
          node-key="id"
          :props="{children:'children',label:'name'}"
          @check="handleCheckChange"
        />
      </div>
    </page-modal>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent , ref , nextTick} from "vue";
import PageContent from '@/components/page-content'
import { contentTableConfig } from  './config/content.config'
import PageSearch from '@/components/page-search'
import PageModal from '@/components/page-modal'
import { formConfig } from './config/search.config'
import { modalConfig } from './config/modal.config'
import { usePageModal } from '@/hooks/use-page-modal'
import { usePageSearch } from "@/hooks/use-page-search";
import { useStore } from '@/store'
import { mapMenusLeafKeys } from '@/utils/map-menus'
import { ElTree } from 'element-plus'

export default defineComponent({
  name: 'role',
  components:{
    PageContent,
    PageSearch,
    PageModal,
  },
  setup() {
    //使用hooks
    const [pageContentRef,handleResetClick,handleQueryClick] = usePageSearch();

    //处理pageModal的hook
    const elTreeRef = ref<InstanceType<typeof ElTree>>()
    const editCallback = (item: any) => {
      const leafKeys = mapMenusLeafKeys(item.menuList)
      // console.log(leafKeys)
      nextTick(()=>{
         elTreeRef.value?.setCheckedKeys(leafKeys,false)
      })

    }

    const [pageModalRef,defaultInfo,handleNewData,handleEditData] =
      usePageModal(undefined,editCallback);

    const store = useStore();
    const menus = computed(() => store.state.entireMenu)
    const otherInfo = ref({})
    const handleCheckChange = (data1: any,data2: any) => {
      const checkedKeys = data2.checkedKeys
      const halfCheckedKeys = data2.halfCheckedKeys
      // console.log(checkedKeys,halfCheckedKeys)
      const menuList = [...checkedKeys,...halfCheckedKeys]
      otherInfo.value = { menuList }
    }
    return {
      contentTableConfig,
      formConfig,
      modalConfig,
      pageModalRef,
      defaultInfo,
      handleNewData,
      handleEditData,
      pageContentRef,
      handleResetClick,
      handleQueryClick,
      menus,
      otherInfo,
      handleCheckChange,
      elTreeRef,
    }
  }
})
</script>

<style lang="less" scoped>
.menu-tree{
  padding-left: 25px;
}
</style>
